/*
 * @Author: Shimir 2358520748@qq.com
 * @Date: 2024-06-30 11:49:21
 * @LastEditors: Shimir 2358520748@qq.com
 * @LastEditTime: 2024-06-30 12:51:27
 * @FilePath: /piping/testPipe.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include <cstring>
#include <string>
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>


#define N 2
#define NUM 1024

using namespace std;

void Writer(int wfd)
{
    string s = "Hello.I am a child";
    pid_t id = getpid();
    int number = 0;
    
    char buffer[NUM];
    while(true)
    {
        //构建发送字符串
        buffer[0] = 0;//字符串清空，只是为了提醒阅读代码的人，这个数组的那个做字符串了，，写不写都可以
        snprintf(buffer,sizeof(buffer),"%s %d - %d times",s.c_str(),id,number++);
        //cout << buffer << endl;

        //发送字符串
        write( wfd, buffer, strlen(buffer));//写入文件时，怎么写的怎么算长度，它不是字符串，不需要规定以\0结尾

        sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;
        size_t n = read(rfd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;//作为字符串使用
            cout << "father " << getpid() << " get " << buffer << endl;
        }
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe( pipefd);
    if(n < 0)   return 1;
    
    //cout<<"pipe[0]:"<<pipefd[0]<<" ,pipe[1]:"<<pipefd[1] << endl;
    
    // child->w   father->r
    pid_t id = fork();
    if(id < 0)    return 2;

    else if(id == 0)
    {
        //child->w
        close(pipefd[0]);
        //IPC code
        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    //father->r
    close(pipefd[1]);
    //IPC code
    Reader(pipefd[0]);

    pid_t rid = waitpid(id,nullptr,0); 
    if(rid < 0) return 3;

    close(pipefd[0]);
    return 0;
}